package com.fast.manager.base.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fast.commons.spring.SpringContextHolder;
import com.fast.commons.web.model.AjaxResponse;
import com.fast.commons.web.model.DataGrid;
import com.fast.manager.base.domain.Post;
import com.fast.manager.base.repository.PostMapper;
import com.fast.manager.base.service.PostService;

@Service
public class PostServiceImpl implements PostService {
	
	@Autowired
	private PostMapper mapper ;
	
	@Override
	public AjaxResponse add(Post record) {
		if(this.mapper.existsFileldValue(null, "fullName", record.getFullName()) > 0) 
			return AjaxResponse.failMsg("该角色已存在！") ;
		if(this.mapper.existsFileldValue(null, "code", record.getCode()) > 0) 
			return AjaxResponse.failMsg("该代码已存在！") ;
			
		this.mapper.insertSelective(record);
		
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}

	@Override
	public AjaxResponse delete(long id) {
		this.mapper.deleteByPrimaryKey(id);
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}

	@Override
	public AjaxResponse deleteBatch(Long[] ids) {
		this.mapper.deleteByPrimaryKeys(ids);
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}

	@Override
	public AjaxResponse update(Post record) {
		if(this.mapper.existsFileldValue(record.getId(), "fullName", record.getFullName()) > 0) 
			return AjaxResponse.failMsg("该角色已存在！") ;
		if(this.mapper.existsFileldValue(record.getId(), "code", record.getCode()) > 0) 
			return AjaxResponse.failMsg("该代码已存在！") ;
		
		this.mapper.updateByPrimaryKeySelective(record);
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}

	@Override
	public Post get(long id) {
		return this.mapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Post> getAllList(Post record) {
		return this.mapper.findAllList(record);
	}
	
	@Override
	public DataGrid<Post> datagrid(Post conditions) {
		DataGrid<Post> dg = new DataGrid<Post>();
		
		Map<String, Object> conditionsMap = new HashMap<String, Object>();
		conditionsMap.put("record", conditions);
		conditionsMap.put("offset", dg.getOffset());
		conditionsMap.put("rows", dg.getPageSize());

		List<Post> list = this.mapper.findAllListPage(conditionsMap);
		int count = this.mapper.getCount(conditionsMap);
		dg.setRows(list);
		dg.setTotal(count);

		return dg;
	}

}
